package org.summer.netty.nio;

import lombok.extern.slf4j.Slf4j;
import org.summer.netty.PacketSplicing;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

@Slf4j
public class Server {
    public static void main(String[] args) {
        try {
            ArrayList<SocketChannel> socketChannels = new ArrayList<>();
            ByteBuffer buffer = ByteBuffer.allocate(16);

            final ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));

            for (; ; ) {
                SocketChannel sc = ssc.accept();
                if (sc != null) {
                    log.info("a socket channel connected ... {}", sc);
                    sc.configureBlocking(false);
                    socketChannels.add(sc);
                }
                for (SocketChannel socketChannel : socketChannels) {
                    int read = socketChannel.read(buffer);
                    if (read != 0) {
                        PacketSplicing.byteBuffPrint(buffer);
                        buffer.clear();
                        log.info("after read -> {}", socketChannel);
                    }
                }
            }
        } catch (IOException e) {
            log.error("error -> {}", e.getMessage());
        }
    }
}
